import React, { Dispatch, SetStateAction, useState, useEffect } from 'react'
import { Modal, Form } from 'antd'
import HomeStore from '../../stores/HomeStory'

import { inject, observer } from 'mobx-react'
import SearchForm, { SearchColumnType } from '../form/SearchForm'

import '../../config/dark-theme.less'
import { Add, Update } from '../../api/api'

interface GoodsModalProps {
  HomeStore: HomeStore
  SetVisible: Dispatch<SetStateAction<boolean>>
  Visible: boolean
  Title?: React.ReactNode
  Columns?: SearchColumnType[]
  recode?: any
  url?: string
  method?: string
}

const GoodsModal: React.FC<GoodsModalProps> = (props: GoodsModalProps) => {
  const {
    recode,
    Columns = [],
    SetVisible,
    Visible = false,
    Title = '添加',
    url = '',
    method = 'get',
  } = props
  const [, setFormData] = useState()

  const [form] = Form.useForm()

  const handleOk = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    let editParams = ''
    form
      .validateFields()
      .then((val) => {
        form.resetFields()
        for (let key in val) {
          if (val[key] !== undefined) {
            editParams += key + '=' + val[key] + '&'
          }
        }
        if (!!url) {
          if (method === 'post') {
            editParams += 'userId=10'
            Add(url, editParams)
          } else {
            Update(url, editParams)
          }
        }
        SetVisible(false)
      })
      .catch((info) => {
        console.log('Validate Failed:', info)
      })
  }

  const handleCancel = () => {
    SetVisible(false)
  }

  useEffect(() => {
    form.setFieldsValue(recode)
  }, [form, recode])

  return (
    <>
      <Modal
        title={Title}
        visible={Visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <SearchForm
          {...props}
          Columns={Columns}
          SetDataSource={setFormData}
          Direction='vertical'
          ShowButton={false}
          form={form}
        />
      </Modal>
    </>
  )
}

export default inject('HomeStore')(observer(GoodsModal))
